package com.zankong.tool.zkapp.v8fn.socket_pck;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.zankong.tool.zkapp.util.Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.net.URISyntaxException;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;


/**
 * Created by YF on 2018/6/30.
 */

public class ZKServiceSocket extends Service {
    private Socket mSocket;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Util.log("socket","onCreate");
        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Util.log("socket","onStartCommand");
        String url = intent.getStringExtra("url");
        Util.log("socket",url);
        createSocket(url);
        return super.onStartCommand(intent, flags, startId);
    }

    private void createSocket(String url){
        try {
            mSocket = IO.socket(url);
            mSocket.connect();
            Util.log("socket","connect");
            EventBus.getDefault().post("complete");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private void on (SocketObj socketObj){
        Util.log("socket,on");
        mSocket.on(socketObj.getEvent(), args -> socketObj.getCallBack().invoke(args));
    }

    private void emit (SocketObj socketObj){
        Util.log("socket,emit");
        Util.log("socket,emit",(mSocket == null)+"");
        mSocket.emit(socketObj.getEvent(),socketObj.getObject(),args -> socketObj.getCallBack().invoke(args));
    }

    private void off(){
        mSocket.off();
    }
    private void connect(){
        mSocket.connect();
    }
    private void disconnect(){
        mSocket.disconnect();
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(SocketObj socketObj) {
        Util.log("socket","onMessageEvent");
            switch (socketObj.getMethod()){
                case "on":
                    on(socketObj);
                    break;
                case "emit":
                    emit(socketObj);
                    break;
                case "off":
                    off();
                    break;
                case "connect":
                    connect();
                    break;
                case "disconnect":
                    disconnect();
                    break;
            }
    }
}
